export default{
    namespaced:true,
    state:{
        cartData:[]
    },
    mutations:{
        SET_CART(state,payload){
            // state.cartData=payload
            // state.cartData.push(payload)
            // 判断之前有没有数据
            let target=state.cartData.find(item=>item.id==payload.id)
            // 没有
            if(!target){
                let obj={
                    title:payload.title,
                    price:payload.price,
                    count:1,
                    id:payload.id
                }
                state.cartData.push(obj)
            }else{
                target.count++
            }

        }
    },
    actions:{
        ADD_CART(context,payload){
            // 这么写是为了让学到如何在一个模块得store里面操作另一个store得mu 和ac
            console.log("cart action--",payload)
            context.commit("SET_CART",payload)

            context.commit('product/DECREASE_INVENTORY',payload.id,{root:true})
        }
    },
    getters:{
        // 总价计算
        total(state){
            return (state.cartData.reduce((total, item) => {
                return total += item.price * item.count
            }, 0)).toFixed(2)
        }
    },
    
}